package jmu.edu.yjc.runner;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jmu.edu.yjc.Utils.RedisCache;
import jmu.edu.yjc.constants.SystemConstants;
import jmu.edu.yjc.domain.entity.Keywords;
import jmu.edu.yjc.domain.entity.ScheduleSetting;
import jmu.edu.yjc.domain.vo.common.TypeVo;
import jmu.edu.yjc.job.method.TaskService;
import jmu.edu.yjc.job.scheduled.CronTaskRegistrar;
import jmu.edu.yjc.job.scheduled.SchedulingRunnable;
import jmu.edu.yjc.service.KeywordsService;
import jmu.edu.yjc.service.ScheduleSettingService;
import jmu.edu.yjc.service.answer.QuestionClassifier;
import jmu.edu.yjc.service.impl.KeywordsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yjc
 * @date 2023/3/16 0:00
 */
@Component
@Slf4j
public class InitBeforeStartApp implements CommandLineRunner {
    @Resource
    private RedisCache redisCache;
    @Resource
    private KeywordsService keywordsService;
    @Resource
    private ScheduleSettingService scheduleSettingService;
    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;
    @Override
    public void run(String... args) throws Exception {
        initJob();
        initKeyWords();
    }
    private void initKeyWords() {
        List<Keywords> keywordsList = keywordsService.getAllWordTypeAndCnMean();
        List<TypeVo> typeVoList = new ArrayList<>();
        for (Keywords keyword : keywordsList) {
            String wordType = keyword.getWordType();
            List<String> keywords = keywordsService.queryKeywordsByWordType(wordType);
            redisCache.setCacheObject(wordType,keywords);
            KeywordsServiceImpl.wordMeanCnMap.put(wordType,keyword.getWordMean());
            typeVoList.add(new TypeVo(wordType,keywords.size()));
        }
        redisCache.setCacheObject("typeList",typeVoList);
    }
    private void initJob() {
        LambdaUpdateWrapper<ScheduleSetting> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ScheduleSetting::getJobStatus, SystemConstants.JOB_STATUS_OPEN);
        List<ScheduleSetting> list = scheduleSettingService.list(wrapper);
        for (ScheduleSetting job : list) {
            SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(),job.getMethodName(),job.getMethodParams());
            cronTaskRegistrar.addCronTask(task,job.getCronExpression());
        }
        log.info("定时任务已加载完毕...");
    }
}
